package com.yunzhi.net.utils.rsa;

import java.io.ByteArrayOutputStream;

import javax.crypto.Cipher;

public class RSAUtils {
    public static final String RSA = "RSA";
    public static final String TRANSFORMATION = "RSA/ECB/PKCS1Padding";
    /**
     * RSA 最大加密明文大小
     */
    private static final int MAX_ENCRYPT_BLOCK = 117;
    /**
     * RSA最大解密密文大小
     */
    private static final int MAX_DECRYPT_BLOCK = 128;
    private static final String key = "MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAn7jswOzNvLpen2c0jhkF\n" +
            "ct+skDonPawmgManYY+CZuK9/hZkK65Ja3H8ExrzBS00n/erbCNyAsh/ltM/N6Xj\n" +
            "u53jn7mCgESKU13QPtAk6HwQN83zDJMz7Pu1PL8oxN0XpIdAHQn3BAe/mp4GMMcY\n" +
            "EJ89+NxREKuACWmVC76q75CBsRRUDrSLo446S33yRZ0bgGYL/0YxarLGIdc/IF+Y\n" +
            "44z+loVLH1j1+JYQKGJlRFcHk+M3jZNF0hLpCZhanFYXAHtzBTQly6dW+anqTcrT\n" +
            "G7diZRo/Zdy5Zmj3PGS3aMQ6UtMjvOyBNZNPL3aASW7jCMJ1XE43xSXcquqrMcNB\n" +
            "HG6qCYtSIanZ32M/IJTgd3Yldi7rdtPAs4L0pWghRYEX8ttZ+u3L/x8K/K/6wLu6\n" +
            "2+D6OjX+KejVOCMMZNEqsNJGIO5nO44jmxPfsxLiudJbV+wUi6zN4pV6FWAJcA9v\n" +
            "cWch9k0ipcR3Hga70RE7ElB5P82lJtHvRObV3x3ERIx62BMel5l/osrETBtj+8W3\n" +
            "0n/T46VN8y8q57/leN9sKztEiX7DYarfAsv2Ay2Sw1tLEH9UJS2ArmOJs4GUIYoL\n" +
            "ARuWN199is9397pEF+tj8nsradN/GNjVhXl8G+3TIU3rytCVgi+IllVxAWDVn2wd\n" +
            "H4Zgs6gSBikvdTWA5TLGDt0CAwEAAQ==";

    /**
     * 使用公钥将数据进行分段加密
     *
     * @param data   要加密的数据
     * @return 加密后的 Base64 编码数据，加密失败返回 null
     */
    public static String encryptByPublicKeyNew(String data) {
//        String publicKey = FileIOUtils.getFromAssets(context,"public_key.pem");
        try {
            byte[] bytes = data.getBytes("UTF-8");
            // 创建 Cipher 对象
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            // 初始化 Cipher 对象，加密模式
            cipher.init(Cipher.ENCRYPT_MODE, RSAEncrypt.getPublicKey(key));
            int inputLen = bytes.length;
            // 保存加密的数据
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int offSet = 0, i = 0;
            byte[] cache;
            // 使用 RSA 对数据分段加密
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                    cache = cipher.doFinal(bytes, offSet, MAX_ENCRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(bytes, offSet, inputLen - offSet);
                }
                // 将加密以后的数据保存到内存
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * MAX_ENCRYPT_BLOCK;
            }
            byte[] encryptedData = out.toByteArray();
            out.close();
            // 将加密后的数据转换成 Base64 字符串
            return DataUtils.base64Encode(encryptedData);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
